import Vue from 'vue';
import VueRouter from 'vue-router';
import store from './store/store';
import * as types from './store/types';
import Index from './views/index/Index.vue';
import Form from './views/index/Form.vue';
import Login from './components/Login.vue';
import Test from './views/index/Test.vue';

Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    name: '/',
    component: Index,
  },
  {
    path: '/login',
    name: 'login',
    component: Login,
  },
  {
    path: '/form',
    name: 'form',
    component: Form,
  },
  {
    path: '/test',
    name: 'test',
    component: Test,
  },
];


// 页面刷新时，重新赋值token
if (window.localStorage.getItem('token')) {
  store.commit(types.LOGIN, window.localStorage.getItem('token'));
}

const router = new VueRouter({
  routes,
});

router.beforeEach((to, from, next) => {
  if (to.matched.some(r => r.meta.requireAuth)) {
    if (store.state.token) {
      next();
    } else {
      next({
        path: '/login',
        query: { redirect: to.fullPath },
      });
    }
  } else {
    next();
  }
});

export default router;
